document.addEventListener('DOMContentLoaded', function() {
    const orderDetailsModal = new bootstrap.Modal(document.getElementById('orderDetailsModal'));

    // Status mapping for display
    const DISPLAY_STATUS_MAP = {
        "PENDING": "待处理",
        "SHIPPED": "已发货",
        "PICKED_UP": "已揽收",
        "IN_TRANSIT": "运输中",
        "UNRECEIVED": "未签收",
        "DELIVERED": "已签收",
        "CANCELED": "已取消"
    };

    function getDisplayStatus(status) {
        return DISPLAY_STATUS_MAP[status] || status;
    }

    function getStatusBadgeClass(status) {
        switch (status) {
            case 'PENDING': return 'bg-secondary';
            case 'SHIPPED': return 'bg-info';
            case 'PICKED_UP': return 'bg-info';
            case 'IN_TRANSIT': return 'bg-primary';
            case 'UNRECEIVED': return 'bg-warning';
            case 'DELIVERED': return 'bg-success';
            case 'CANCELED': return 'bg-danger';
            default: return 'bg-secondary';
        }
    }

    document.querySelectorAll('.view-details-btn').forEach(button => {
        button.addEventListener('click', function() {
            const orderId = this.getAttribute('data-order-id');
            console.log('查看订单详情 - Order ID:', orderId);
            
            // 使用普通用户可以访问的API路径
            fetch(`/orders/details/${orderId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(order => {
                    console.log('获取到的订单数据:', order);
                    
                    document.getElementById('modalOrderNumber').textContent = order.orderNumber || '';
                    document.getElementById('modalSenderName').textContent = order.senderName || '';
                    document.getElementById('modalSenderPhone').textContent = order.senderPhone || '';
                    document.getElementById('modalSenderAddress').textContent = order.senderAddress || '';
                    document.getElementById('modalReceiverName').textContent = order.receiverName || '';
                    document.getElementById('modalReceiverPhone').textContent = order.receiverPhone || '';
                    document.getElementById('modalReceiverAddress').textContent = order.receiverAddress || '';
                    document.getElementById('modalPackageType').textContent = order.packageType || '';
                    document.getElementById('modalWeight').textContent = order.weight || '';
                    document.getElementById('modalVolume').textContent = order.volume || '';
                    document.getElementById('modalPrice').textContent = order.price || '';
                    
                    const modalStatusElement = document.getElementById('modalStatus');
                    modalStatusElement.textContent = getDisplayStatus(order.status);
                    modalStatusElement.className = 'badge ' + getStatusBadgeClass(order.status);

                    document.getElementById('modalCreatedAt').textContent = order.createdAt ? new Date(order.createdAt).toLocaleString() : '';
                    document.getElementById('modalUpdatedAt').textContent = order.updatedAt ? new Date(order.updatedAt).toLocaleString() : '';

                    orderDetailsModal.show();
                })
                .catch(error => {
                    console.error('获取订单详情失败:', error);
                    alert('获取订单详情失败：' + error.message);
                });
        });
    });

    document.querySelectorAll('.sign-for-parcel-btn').forEach(button => {
        button.addEventListener('click', function() {
            const orderId = this.getAttribute('data-order-id');
            console.log('签收包裹 - Order ID:', orderId);

            if (confirm('您确定要签收此包裹吗？')) {
                const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
                const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

                fetch(`/orders/sign-for/${orderId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        [csrfHeader]: csrfToken
                    },
                    body: JSON.stringify({ status: 'DELIVERED' })
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('签收失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        alert('包裹签收成功！');
                        location.reload(); // 刷新页面以显示更新后的数据
                    } else {
                        alert('签收失败：' + (data.message || '未知错误'));
                    }
                })
                .catch(error => {
                    console.error('签收包裹时发生错误:', error);
                    alert('签收失败：' + error.message);
                });
            }
        });
    });

    // 取消订单按钮事件处理
    document.querySelectorAll('.cancel-received-order-btn').forEach(button => {
        button.addEventListener('click', function() {
            const orderId = this.getAttribute('data-order-id');
            const orderNumber = this.getAttribute('data-order-number');
            console.log('取消收件订单 - Order ID:', orderId, 'Order Number:', orderNumber);

            if (confirm(`您确定要取消订单 ${orderNumber} 吗？此操作不可恢复！`)) {
                const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
                const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

                fetch(`/orders/cancel/${orderId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        [csrfHeader]: csrfToken
                    },
                    body: JSON.stringify({ status: 'CANCELED' })
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('取消订单失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        alert('订单取消成功！');
                        location.reload(); // 刷新页面以显示更新后的数据
                    } else {
                        alert('取消订单失败：' + (data.message || '未知错误'));
                    }
                })
                .catch(error => {
                    console.error('取消订单时发生错误:', error);
                    alert('取消订单失败：' + error.message);
                });
            }
        });
    });
}); 